import logging.handlers
import os
import sys


class GetLogging:
    logger = None
    filename = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    @classmethod
    def get_logging(cls):
        if cls.logger is None:
            # 获取日志器
            cls.logger = logging.getLogger()

            # 设置日志器级别
            cls.logger.setLevel(logging.INFO)

            # 获得处理器控制台
            sh = logging.StreamHandler(sys.stdout.reconfigure(encoding='utf-8'))

            # 获得处理器 所有级别文件 以时间分隔
            th = logging.handlers.TimedRotatingFileHandler(filename=os.path.join(cls.filename + "/log/all_test.log"),
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=30,
                                                           encoding="utf-8")
            th.setLevel(logging.DEBUG)

            # 获得处理器 error以上级别文件 以时间分隔
            eh = logging.handlers.TimedRotatingFileHandler(filename=os.path.join(cls.filename + "/log/error_test.log"),
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=5,
                                                           encoding="utf-8")
            eh.setLevel(logging.ERROR)

            # 设置格式器
            fmt = "%(asctime)s %(levelname)s [%(name)s] [%(filename)s (%(funcName)s:%(lineno)d)] - %(message)s"
            fm = logging.Formatter(fmt)

            # 将格式器添加到处理器（控制台）
            sh.setFormatter(fm)

            # 将格式器添加到处理器（文件）
            th.setFormatter(fm)
            eh.setFormatter(fm)

            # 将处理器添加到日志器中
            cls.logger.addHandler(sh)
            cls.logger.addHandler(th)
            cls.logger.addHandler(eh)

        return cls.logger